class_name PlayerHandler
extends Node

const HAND_DRAW_INTERVAL := 0.25
const HAND_DISCARD_INTERVAL := 0.25

signal player_mana_changed

@export var max_mana:int
var cur_mana:int
@export var hand: Hand

var character: CharacterStats

func _ready() -> void:
	Events.card_played.connect(_on_card_played)
	cur_mana = max_mana

func start_battle(char_stats: CharacterStats) -> void:
	character = char_stats
	# 初始化牌库并洗牌
	character.draw_pile = character.deck.duplicate(true)
	character.draw_pile.shuffle()
	# 初始化弃牌堆
	character.discard_pile = CardPile.new()
	start_turn()
	
func start_turn() -> void:
	character.block = 0
	character.reset_mana()
	draw_cards(character.cards_per_turn)

func end_turn() -> void:
	discard_cards()
	

func reshuffe_deck_from_discard() -> void:
	if not character.draw_pile.empty():
		return
	while  not character.discard_pile.empty():
		character.draw_pile.add_card(character.discard_pile.draw_card())
		
	character.draw_pile.shuffle()

func discard_cards() -> void:
	var tween := create_tween()
	for card_ui in hand.get_children():
		tween.tween_callback(character.discard_pile.add_card.bind(card_ui.card))
		tween.tween_callback(hand.discard_card.bind(card_ui))
		tween.tween_interval(HAND_DISCARD_INTERVAL)
		
	tween.finished.connect(
		func():
			Events.player_hand_discarded.emit()
	)

func draw_card() -> void:
	reshuffe_deck_from_discard()
	hand.add_card(character.draw_pile.draw_card())
	reshuffe_deck_from_discard()

func draw_cards(amount: int) -> void:
	var tween := create_tween()
	for i in range(amount):
		tween.tween_callback(draw_card)
		tween.tween_interval(HAND_DRAW_INTERVAL)
	
	tween.finished.connect(
		func(): Events.player_hand_drawn.emit()
	)
		
func _on_card_played(card: Card) -> void:
	character.discard_pile.add_card(card)
	
	
